package com.oocl.homework.crm.command;

import com.oocl.homework.crm.datastruct.Executeable;
import com.oocl.homework.crm.model.Filterable;
import com.oocl.homework.crm.model.Result;
import com.oocl.homework.crm.util.CommandUtil;

public abstract class Command<T>{
	
	private Executeable<T> executeable;
	
	protected String command;
	
	private Filterable filterable;
	
	private String[] commandParameters;
	private String[] commandParameterAttributes;
	
	protected String commandData;
	
	protected Result result;
	
	public Command(String command){
		this.command = command;
		result = new Result();
	}
	
	public String[] getCommandParameters() {
		return commandParameters;
	}
	
	
	public Result getResult(){
		return result;
	}
	

	public String getCommandData(){
		return commandData;
	}
	public void setCommand(String command) {
		this.command = command;
	}

	public void setCommandParameters(String[] commandParameters) {
		this.commandParameters = commandParameters;
	}

	public String[] getCommandParameterAttributes() {
		return commandParameterAttributes;
	}

	

	
	 
	 protected String[] splitCommandParameter(){
		 return commandParameters=getCommandParamterString().split(",");
	 }
	 
	 protected Result splitCommandParameterAttributes(){
		splitCommandParameter();
		result.setCode(1);
		commandParameterAttributes = new String[commandParameters.length];
		for (int i = 0; i < commandParameters.length; i++) {
			if(commandParameters[i].contains(":")){
				commandParameterAttributes[i] = commandParameters[i].split(":")[0];
			}else{
				result.setCode(-1);
				result.setMessage("Unrecognized paramter:"+commandParameters[i]);
				return result;
			}
				
		}
		return result;
	 }
	 
	 private String getCommandParamterString(){
		 String[] commandStrings = command.split(" ");
		 return commandStrings[commandStrings.length-1];
	 }
	 
	 
	 
	 
	 
	 
	 public void filter(Filterable filterable){
		 	if(command.length()<3){
		 		result.setCode(-1);
		 		result.setMessage("Missing Parameters");
		 		return;
		 	}
		 	result.setCode(1);
			this.filterable = filterable;
		}
		
	 protected void filterId(){
		 String[] commandStringList = command.split(" ");
			if(commandStringList.length<2){
				result.setCode(-1);
				result.setMessage("need id");
				return;
			}
			if(!CommandUtil.isNumeric(commandStringList[1])){
				result.setCode(-1);
				result.setMessage("id must be digit");
				return;
			}else{
				commandData = commandStringList[1];
			}
	 }
	 
		public final void execute(Executeable<T> executeable, T t){
			if(result.getCode()==-1){
				display();
			}else{
				executeCommand(executeable,t);
			}
		}
		
		public void  executeCommand(Executeable<T> executeable,T t){
			this.executeable = executeable;
		}
		
		 public void display(){
			 
			 System.out.println(result.toString());
		 }
	 
		 


}
